import * as THREE from 'three';
// 引入性能监视器
import Stats from 'three/addons/libs/stats.module.js'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
let controls,cubeArr = [],stats


const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

controls = new OrbitControls( camera, renderer.domElement );
camera.position.set(0,5,10) // 设置摄像机的位置

// 加入性能监视器
function createStats() {
    stats = new Stats()
    stats.setMode(0) // 0 每秒刷新帧数 1,每帧用时, 2,内存占用
    stats.domElement.style.position = 'fixed'
    stats.domElement.style.left = '0'
    stats.domElement.style.top = '0'
    document.body.appendChild(stats.domElement)

}
// 创建多个位置大小随机的立方体
function createCube() {
    const list = []
    // 数据
    for(let i= 0; i<10; i++){
        list.push({
            col: `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`,
            width: Math.floor(Math.random() * (2) + 1),
            height: Math.floor(Math.random() * (2) + 1),
            deep: Math.floor(Math.random() * (2) + 1),
            x: Math.floor(Math.random() *(5 - -5 + 1 ) -5),
            y: Math.floor(Math.random() *(5 - -5 + 1 ) + -5),
            z: Math.floor(Math.random() *(5 - -5 + 1 ) + -5)
        })
    }
    // 创建物体
    list.forEach(({col,width,height,deep,x,y,z}) => {
        const geometry = new THREE.BoxGeometry(width,height,deep)
        const material = new THREE.MeshBasicMaterial({color: col})
        const cube = new THREE.Mesh(geometry, material)
        cube.position.set(x,y,z)
        cubeArr.push(cube)
        scene.add(cube)
    })
}
// 双击屏幕删除一个立方体
// 删除顺序: 按照加入cubeArr数组里顺序从头删


function createAxes (){ // 总体的
    const axesHelper = new THREE.AxesHelper(20)
    scene.add(axesHelper)
}
function animate() {
	requestAnimationFrame( animate );
    stats.update()
	controls.update();
    cubeArr.forEach(cube => {
        cube.rotation.x += 0.01
        cube.rotation.y += 0.01
    })
	renderer.render( scene, camera );
}
function resize () {
    window.addEventListener('resize', () => {
        renderer.setSize(window.innerWidth,window.innerHeight)
        camera.aspect = window.innerWidth/window.innerHeight
        camera.updateProjectionMatrix()
    })
}

resize()
createStats()
createCube()
createAxes()
animate()






